const express = require('express');
const router = express.Router();
const pool = require('../config/bd');

router.post('/comment/likes', async (req, res) => {
  const { commentId, userId, isLike } = req.body;
  const connection = await pool.getConnection();

  if (!commentId || !userId || typeof isLike === 'undefined') {
    connection.release();
    return res.status(400).json({ code: 400, message: '参数缺失' });
  }

  try {
    await connection.beginTransaction();

    // =========== 类型验证优化 ===========
    const [commentCheck] = await connection.execute(`
      SELECT 
          (SELECT comment_type FROM child_comments WHERE id=? AND comment_type='child') AS child_type,
          (SELECT comment_type FROM comments WHERE id=? AND comment_type='main') AS main_type
  `, [commentId, commentId]);

    // 确定评论类型
    let type;
    if (commentCheck[0].child_type) {
      type = 'child';
    } else if (commentCheck[0].main_type) {
      type = 'main';
    } else {
      await connection.rollback();
      return res.status(404).json({ code: 404, message: '评论不存在' });
    }

    // =========== 外键约束适配 ===========
    const parentTable = type === 'main' ? 'comments' : 'child_comments';

    // 强制验证父表存在性[3](@ref)
    const [fkCheck] = await connection.execute(
      `SELECT 1 FROM ${parentTable} 
       WHERE id=? AND comment_type=? 
       LIMIT 1 FOR UPDATE`,
      [commentId, type]
    );
    if (!fkCheck.length) {
      await connection.rollback();
      return res.status(400).json({
        code: 40061,
        message: `数据关联异常（${parentTable}表未找到ID:${commentId} Type:${type}）`
      });
    }

    // =========== 锁机制增强 ===========
    const [existingLike] = await connection.execute(
      `SELECT is_like FROM comment_likes 
       WHERE user_id=? AND comment_id=? AND comment_type=? 
       FOR UPDATE`, // 改为排他锁[6](@ref)
      [userId, commentId, type]
    );
    const alreadyLiked = existingLike.length > 0 && existingLike[0].is_like === 1;

    if (isLike !== alreadyLiked) {
      await connection.rollback();
      return res.status(409).json({ code: 409, message: '操作冲突' });
    }

    // =========== 事务操作 ===========
    try {
      if (!isLike) {
        await connection.execute(
          `INSERT INTO comment_likes (user_id, comment_id, comment_type, is_like)
           VALUES (?, ?, ?, 1)
           ON DUPLICATE KEY UPDATE is_like=1`,
          [userId, commentId, type]
        );
      } else {
        await connection.execute(
          `DELETE FROM comment_likes 
           WHERE user_id=? AND comment_id=? AND comment_type=?`,
          [userId, commentId, type]
        );
      }

      const delta = isLike ? -1 : 1;
      await connection.execute(
        `UPDATE ${parentTable} 
         SET like_count = GREATEST(like_count + ?, 0) 
         WHERE id=?`,
        [delta, commentId]
      );

      const [updatedCount] = await connection.execute(
        `SELECT like_count FROM ${parentTable} WHERE id=?`,
        [commentId]
      );
      await connection.commit();

      res.json({
        code: 200,
        data: {
          likeCount: updatedCount[0].like_count,
          isLiked: !isLike,
          commentType: type
        },
        message: '操作成功'
      });

    } catch (sqlErr) {
      // 外键错误专项处理[3](@ref)
      if (sqlErr.errno === 1452) {
        console.error('外键约束诊断:', {
          parentTable,
          expectedType: type,
          actualData: await connection.execute(
            `SELECT comment_type FROM ${parentTable} WHERE id=?`,
            [commentId]
          )
        });
        await connection.rollback();
        return res.status(400).json({
          code: 40062,
          message: '数据版本冲突，请刷新页面'
        });
      }
      throw sqlErr;
    }

  } catch (err) {
    await connection.rollback();
    console.error('操作失败:', err);
    res.status(500).json({
      code: 500,
      message: process.env.NODE_ENV === 'production'
        ? '系统错误'
        : err.message
    });
  } finally {
    connection.release();
  }
});

module.exports = router;